package com.meet.exception;

import com.meet.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Result handle(HttpServletRequest request, MethodArgumentNotValidException e) {

        String requestUri = request.getRequestURI();
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String tips = "参数不合法";
        if (errors.size() > 0) {
            tips = ((ObjectError) errors.get(0)).getDefaultMessage();
        }

        return new Result(false, CommonErrors.INVALID_PARAM.getCode(), tips);
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public Result handle(HttpServletRequest request, HttpMessageNotReadableException e) {

        String requestUri = request.getRequestURI();
        String tips = "请求参数为空";
        log.error("http请求异常：", e);
        return new Result(false, CommonErrors.INVALID_PARAM.getCode(), tips);
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result handle(HttpServletRequest request, Exception e) {

        String requestUri = request.getRequestURI();
        if (BusinessException.class.isAssignableFrom(e.getClass())) {

            BusinessException be = (BusinessException) e;
            return new Result(false, be.getCode(), be.getMessage());

        } else {

            log.error("发生错误", e);
            return new Result(false, CommonErrors.UNDEFINED.getCode(), "服务器开小差了，请联系客服。");

        }
    }

}
